// @flow
import React, { Component } from 'react'
import { Form, Select, Input, Modal, message, InputNumber } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'

const FormItem = Form.Item
const Option = Select.Option
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}
type Props = {
  deviceId: number,
  data: Object,
  form: Object,
  refreshVar: Function,
  removeNode: Function
}

type States = {
  variableType: Array<Object>,
  visible: boolean,
  confirmLoading: boolean
}

class VarEdit extends Component {
  props: Props
  state: States
  handleSubmit: Function
  closeModal: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      variableType: [],
      visible: true,
      confirmLoading: false
    }

    this.handleSubmit = this.handleSubmit.bind(this)
    this.closeModal = this.closeModal.bind(this)
  }

  componentWillMount () {
    this.getVariableType()
  }
  getVariableType () {
    universalFetch(`${__SERVICE_API__}device/conditions?types=variableType`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          variableType: json.result.variableType
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  closeModal () {
    this.setState({
      visible: false
    })
    this.props.removeNode()
  }
  handleSubmit () {
    const varForm = this.props.form
    const { data, deviceId } = this.props
    varForm.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        confirmLoading: true
      })
      const type = fieldsValue.type
      let dataType = ''
      if (type === '不显示') {
        dataType = 0
      } else if (type === '普通指标') {
        dataType = 1
      } else if (type === '关键指标') {
        dataType = 2
      } else {
        dataType = type
      }
      const values = {
        ...fieldsValue,
        type: dataType,
        variableName: fieldsValue.kmxVariableName,
        variableNameEn: fieldsValue.kmxVariableNameEn,
        variableType: fieldsValue.kmxVariableType,
        unit: fieldsValue.kmxUnit,
        monitorPointId: data.monitorPointId
      }
      universalFetch(`${__SERVICE_API__}device/devices/monitors/variables/${data.id}`, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: 'PUT',
        body: JSON.stringify(values)
      })
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        message.success('变量修改成功')
        this.props.refreshVar(deviceId, data.monitorPointId)
        this.setState({
          visible: false,
          confirmLoading: false
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
        this.setState({
          confirmLoading: false
        })
        message.error('变量修改失败: ' + error.message)
      })
    })
  }
  checkNum (rule, value, callback) {
    const checkReg = /^[a-zA-Z0-9_]*$/
    if (value && !checkReg.test(value)) {
      callback('只能输入英文、数字和下划线')
    } else {
      callback()
    }
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const { variableType, visible, confirmLoading } = this.state
    const { data } = this.props
    const type = data.type
    let dataType = ''
    if (type === 0) {
      dataType = '不显示'
    } else if (type === 1) {
      dataType = '普通指标'
    } else if (type === 2) {
      dataType = '关键指标'
    }
    return (
      <Modal
        title='编辑变量'
        visible={visible}
        onOk={this.handleSubmit}
        onCancel={this.closeModal}
        confirmLoading={confirmLoading}
        >
        <Form>
          <FormItem {...formItemLayout} label='KMX 名字' hasFeedback>
            {getFieldDecorator('kmxVariableName', {
              rules: [
                { required: true, message: '请填写KMX 名字', whitespace: true }
              ],
              initialValue: data.kmxVariableName
            })(
              <Input placeholder='请填写KMX 名字' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='KMX 名字en' hasFeedback>
            {getFieldDecorator('kmxVariableNameEn', {
              rules: [
                { required: true, message: '请填写KMX 名字en', whitespace: true },
                { validator: this.checkNum }
              ],
              initialValue: data.kmxVariableNameEn
            })(
              <Input placeholder='请填写KMX 名字en' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='KMX 类型'>
            {getFieldDecorator('kmxVariableType', {
              rules: [
                { required: true, message: '请选择KMX 类型' }
              ],
              initialValue: data.kmxVariableType
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} placeholder='请选择KMX 类型'>
                {
                  variableType.map((v, i) => {
                    return <Option key={i} value={v.value}>{v.label}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='KMX 单位' hasFeedback>
            {getFieldDecorator('kmxUnit', {
              initialValue: data.kmxUnit
            })(
              <Input placeholder='请填写KMX 单位' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='变量类型' hasFeedback>
            {getFieldDecorator('type', {
              initialValue: dataType
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} placeholder='请选择变量类型'>
                <Option key='1' value='1'>普通指标</Option>
                <Option key='2' value='2'>关键指标</Option>
                <Option key='0' value='0'>不显示</Option>
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='最大值' hasFeedback>
            {getFieldDecorator('max', {
              initialValue: data.max
            })(
              <InputNumber placeholder='请填写最大值' style={{ width: '100%' }} />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='最小值' hasFeedback>
            {getFieldDecorator('min', {
              initialValue: data.min
            })(
              <InputNumber placeholder='请填写最小值' style={{ width: '100%' }} />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='标准值' hasFeedback>
            {getFieldDecorator('standardValue', {
              initialValue: data.standardValue
            })(
              <Input placeholder='请填写标准值' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='更新频率' hasFeedback>
            {getFieldDecorator('frequency', {
              initialValue: data.frequency
            })(
              <InputNumber placeholder='请输入频率,仅限数字' style={{ width: '100%' }} />
            )}
          </FormItem>
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(VarEdit)
